const {
  getUser,
  getRepos,
  getDocs,
  getDocsDetails,
  getGroupInfo
} = require("../service/list");
const {
  isLogin
} = require("../service/isLogin");
const inquirer = require("inquirer");
const {
  extractKeys,
  db
} = require("../utils");
const writeFileTree = require("../utils/writeFileTree");
const path = require("path");
const log = require("../utils/log");
async function chooseGroups() {
  var userRes = await getUser();
  var {
    id
  } = userRes.data.data;
  let groupRes = await getGroupInfo(id);
  let datas = [];

  let data = extractKeys(
    groupRes.data.data,
    ["id", "name", "description"],
    (row) => {
      row.value = {
        id: row.id,
        name: row.name
      };
    }
  );

  const Prompt = {
    name: "data",
    type: "list",
    message: `请选择哪个团队`,
    choices: [...data],
  };
  let groupData = (await inquirer.prompt([Prompt])).data;

  return await usersRepos(groupData.id)
}
async function chooseRepos() {
  var userRes = await getUser();
  var {
    id
  } = userRes.data.data;
  return await usersRepos(id);
}

async function usersRepos(id) {
  var ReposRes = await getRepos(id);
  let data = extractKeys(
    ReposRes.data.data,
    ["id", "name", "description"],
    (row) => {
      row.value = {
        id: row.id,
        name: row.name
      };
    }
  );

  const Prompt = {
    name: "data",
    type: "list",
    message: `请选择知识库`,
    choices: [...data],
  };
  return (await inquirer.prompt([Prompt])).data;
}


async function chooseType() {
  const Prompt = {
    name: "type",
    type: "list",
    message: `选择类型`,
    choices: [{
      value: 0,
      name: '我的知识库'
    }, {
      value: 1,
      name: '团队'
    }],
  };
  var result = await inquirer.prompt([Prompt]);
  return result
}
async function chooseDocs(data) {

  var DocsData = extractKeys(
    data,
    ["id", "title", "slug"],
    (row) => {
      row.value = row.slug;
      row.name = row.title;
    }
  );
  const Prompt = {
    name: "slug",
    type: "list",
    message: `请选择文章`,
    choices: DocsData,
  };
  var result = await inquirer.prompt([Prompt]);
  return [result]
}
async function downDocsing(data, docsId) {
  //  row.value = row.slug;
  //  row.name = row.title;
  var treeData = {};
  var len = data.length;
  for (let index = 0; index < data.length; index++) {
    var docsInfo = data[index];
    var DocsDetailsRes = await getDocsDetails(docsId, docsInfo.slug);
    var {
      book,
      title,
      body,
      format,
      body_html
    } = DocsDetailsRes.data.data;

    // console.log(body_html)
    var title = format === "lake" ? title + ".md" : title;
    treeData[title] = body.split('<br />').join('\r\n');
    log.progressStatus(`正在下载中: ${((index+1)/len*100).toFixed(2)}%`)
  }
  log.success(`\r\n下载完成`);
  return treeData
}

async function downDocs(path, data) {
  await writeFileTree(path, data);
}

async function saveDownData(docsData, repos) {
  var data = docsData.reduce((pre, data) => {
    var {
      title,
      format
    } = data;
    var title = format === "lake" ? title + ".md" : title;
    pre[title] = {
      id: data.id,
      slug: data.slug,
      title: data.title,
      parentDir: repos.name,
      parentId: repos.id,
      book_id: data.book_id
    };
    return pre;
  }, {})

  await db.setVal(repos.name, data)
}

module.exports = async function (args) {
  try {
    if (!(await isLogin())) return;

    let res = await chooseType();
    let repos;
    if (res.type == 1) {
      repos = await chooseGroups(); //拿到知识库的id
    } else {
      repos = await chooseRepos(); //拿到知识库的id
    }

    var DocsRes = await getDocs(repos.id); // 获取所有的文章
    var downDocsingData = null;
    if (args.all) { // 下载所有文章
      downDocsingData = await downDocsing(DocsRes.data.data, repos.id)
    } else {
      // 下载单篇文章
      let downData = await chooseDocs(DocsRes.data.data);
      // 下载中
      downDocsingData = await downDocsing(downData, repos.id)
    }
    // 保存到本地
    await downDocs(path.join(process.cwd(), args.path, repos.name), downDocsingData)
    // 保存到数据库

    await saveDownData(DocsRes.data.data, repos)

  } catch (error) {
    console.log(error);
  }
};